<template>
  <div class="login">
    <div class="login_bg">
      <div class="login_title" >{{ $productName }}</div>
      <div class="login_title" style="margin-top: 10px;">3-minute application</div>
      <div class="login_title" style="margin-top: 10px;">1-minute disbursement</div>
    </div>
    <div class="login_box">
      <div class="login_form">
        <div class="form_item" style="display:flex;align-items: center;">
          <span class="symbol_text">
            <span>+63</span>
          </span>
          <input v-model="loginForm.phone" maxlength="13" type="tel" oninput="value = value.replace(/[^\d]/g, '');"
                 :placeholder="$t('请输入手机号码')"/>
        </div>
        <div class="form_item">
          <div style="display: flex">
            <input v-model="loginForm.smsCode" type="tel" style="width:50%" maxlength="4"
                   :placeholder="$t('请输入验证码')"
                   oninput="value = value.replace(/[^\d]/g, '');"/>
            <div class="btn_code" :disabled="sendCodeDisabled" @click="sendCode"
                 size="small">
              <span v-if="buttonType ==='default'" style="padding: 0 20px;">{{ codeNum }}s</span>
              <span v-else>{{ codeText }}</span>
            </div>
          </div>
        </div>

      </div>

      <div class="apply_now">
        <van-button class="confirm"  round :loading="loginBtnLoading" type="primary" @click="onLogin">{{ $t('登录') }}
        </van-button>
      </div>
      <div class="policy" id="login_footer">
        <van-checkbox v-model="checkedServe" shape="square" icon-size="16px" style="display: inline-block;margin-right: 3px">
        </van-checkbox>
        <span> I have read and agreed to the  <a @click="serveContentShow = true"
                                                 style="color: #15B3B2">Privacy Agreement and Disclosure of Rights</a></span>
      </div>
    </div>


    <van-popup v-model:show="serveContentShow" position="bottom" :style="{ height: '80%' }" closeable
               close-icon="close">
      <div
          style="width: 100%;height: 100%;padding: 50px 10px 20px 10px;background-color: #FFFFFF;box-sizing: border-box">
        <iframe style="width: 100%;height: 100%;background-color: #FFFFFF; border: none;
    margin: 0;
    padding: 0;
    overflow: hidden;" src="https://www.cashbilis.top/cash_mabilis_policy.html"></iframe>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {ref, reactive, onMounted,} from 'vue'
import {useI18n} from 'vue-i18n'
import {apiSendCode, apiOnLogin} from "@/api/login";
import {
  userInfoVerify,
} from '@/api/home'
import {
  Toast
} from "vant";
import router from "@/router";
import {debounce, processNext, upLoadAdjustPoint} from '@/utils/tool'
import {useStore} from "vuex";

export default {
  setup() {
    const {t} = useI18n()
    const store = useStore()
    let checkedServe = ref(false)
    let codeNum = ref(60)
    let buttonType = ref('primary')
    let codeText = ref(t('发送验证码'))
    const serveContentShow = ref(false)
    const timer = ref(null)
    const loanProductName = localStorage.getItem('productName')
    const sendCodeDisabled = ref(false)
    const loginBtnLoading = ref(false)
    const loginForm = reactive({
      phone: '',
      smsCode: '',
      osType: 'h5'
    })
    // 是否调用短信api
    const isSmsApiCode = ref(false)
    // 校验登录表单
    const verificationForm = () => {
      let message = ''
      const {phone, smsCode} = loginForm
      if (!phone) message = t('请输入手机号码')
      if (!smsCode) message = t('请输入验证码')
      if (phone.length < 9) message = t('请输入正确的手机号码')
      if (message) {
        Toast({
          message: message
        })
        return false
      } else {
        return true
      }
    }
    //发送验证码
    const sendCode = debounce(
        async () => {
          if (buttonType.value === 'default') return
          if (!loginForm.phone) {
            Toast({
              message: t('请输入手机号码')
            })
            return
          }
          if (loginForm.phone.length < 9) {
            Toast({
              message: t('请输入正确的手机号码')
            })
            return
          }
          if (!checkedServe.value) return Toast({message: t('请先勾选同意协议')})
          if (process.env.NODE_ENV === 'production' && !window.android) {
            return Toast('System error 0x11100')
          }
          sendCodeDisabled.value = true
          const res = await apiSendCode({
            smsType: '1',
            phone: loginForm.phone,
            loanProductName: loanProductName
          })
          if (res.code === 1) {
            sendCodeDisabled.value = false
            buttonType.value = 'default'
            timer.value = setInterval(() => {
              codeNum.value--
              if (codeNum.value === 0) {
                clearInterval(timer.value)
                codeNum.value = 60
                buttonType.value = 'primary'
              }
            }, 1000)
          } else {
            sendCodeDisabled.value = false
          }
        }
    )
    // 登录处理
    const onLogin = async () => {
      if (process.env.NODE_ENV === 'production' && !window.android) {
        return Toast('System error 0x11100')
      }
      if (!checkedServe.value) return Toast({message: t('请先勾选同意协议')})
      if (verificationForm()) {
        loginBtnLoading.value = true
        // 设备系统
        const u = navigator.userAgent
        const osType = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 ? 'android' : 'ios';
        const params = {
          ...loginForm,
          osType,
          smsType: '1',
          loanProductName: loanProductName,
          userType: isSmsApiCode.value ? 1 : 0
        }
        const res = await apiOnLogin(params)
        if (res.code === 1 || res.code === 10) {
          const {userId, token} = res.data
          localStorage.setItem('token', token)
          localStorage.setItem('userId', userId)
          localStorage.setItem('phone', loginForm.phone)
          const userRes = await userInfoVerify()
          if (userRes.code === 1) {
            if (window.android) {
              window.android.login(JSON.stringify({...res.data, phone: loginForm.phone}))
            }
            upLoadAdjustPoint({eventName: 'd3reh5'})
            const {personalInfo} = userRes.data
            // 如果有填写过资料 拦截去首页
            if (personalInfo) {
              router.replace('/hScmlvxSUkDQ/UjRzDSClllpS')
            } else {
              processNext('')
            }
          }
          loginBtnLoading.value = false
        } else {
          loginBtnLoading.value = false
        }
      }
    }

    const checkChange = (val) => {
      checkedServe.value = val
    }
    onMounted(() => {
      // 清除loading
      store.dispatch('changeLoading', false)
    })

    return {
      checkedServe,
      loanProductName,
      onLogin,
      sendCode,
      loginForm,
      codeNum,
      buttonType,
      codeText,
      checkChange,
      sendCodeDisabled,
      serveContentShow,
      loginBtnLoading,
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  background-size: 100% 100%;
  position: relative;
  background-color: #FFFFFF;
  height: 100vh;

}

.login_bg {
  background-image: url("../../assets/login_bg.png");
  background-size: 100% 100%;
  width: 100%;
  height: 300px;
  box-sizing: border-box;
  padding-top: 70px;
  padding-left: 15px;
  font-family: Inter, Inter;
  font-weight: normal;
  font-size: 18px;
  color: #FFFFFF;
  line-height: 24px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  .login_title {
    text-align: left;
  }

  .login_title_tips {
    font-size: 16px;
    color: #838693;
    text-align: center;
    padding: 0 30px;
  }
}

.login_box {
  padding: 40px 20px;
  margin-top: -60px;
  background-color: #FFFFFF;
  border-radius: 10px;
  .login_form {
    .title {
      font-size: 16px;
      color: #FFFFFF;
      padding: 0 30px;
    }

    .form_item {
      padding: 10px;
      position: relative;
      margin-bottom: 25px;
      box-sizing: border-box;
      border-radius: 5px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
      .symbol_text {
        font-size: 18px;
        margin-right: 5px;
        font-weight: 600;
        border-right: 2px solid #333333;
        padding-right: 5px;
        line-height: 18px;
      }

      .symbol {
        vertical-align: middle;
      }

      input {
        border: 0;
        font-size: 16px;
        flex: 1;
        border-radius: 10px;
        box-sizing: border-box;
        width: 100%;
        height: 25px;
      }
      input::placeholder {
        color: #BCBCBC;
      }
      .text {
        width: 100%;
        padding: 5px 0 0 10px;
        box-sizing: border-box;
        font-size: 12px;
        color: #999999;
      }

      .btn_code {
        float: right;
        margin-left: 5%;
        margin-right: 10px;
        line-height: 26px;
        font-size: 16px;
        text-align: center;
        color: #15B3B2
      }
    }

  }


  .apply_now {
    text-align: center;
    .agreement {
      font-size: 12px;
      margin-left: 10px;
      color: #828282;

      .active {
        color: #6842FF;
      }
    }

    .confirm {
      margin: 20px 0;
      width: 100%;
      font-size: 22px;
      font-weight: bold;
    }
  }
}

.policy {
  padding: 8px 20px;
  line-height: 18px;
  font-size: 12px;
  width: 100%;
  box-sizing: border-box;
  text-align: center;
}
</style>
